package com.cens.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.cens.common.exception.NoStockException;
import com.cens.common.to.mq.OrderTo;
import com.cens.common.to.mq.StockDetailTo;
import com.cens.common.to.mq.StockLockedTo;
import com.cens.common.utils.R;
import com.cens.mall.ware.entity.WareOrderTaskDetailEntity;
import com.cens.mall.ware.entity.WareOrderTaskEntity;
import com.cens.mall.ware.feign.CommodityFeignService;
import com.cens.mall.ware.feign.OrderFeignService;
import com.cens.mall.ware.service.WareOrderTaskDetailService;
import com.cens.mall.ware.service.WareOrderTaskService;
import com.cens.mall.ware.vo.OrderItemVo;
import com.cens.mall.ware.vo.OrderVo;
import com.cens.mall.ware.vo.SkuHasStockVo;
import com.cens.mall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cens.common.utils.PageUtils;
import com.cens.common.utils.Query;

import com.cens.mall.ware.dao.WareSkuDao;
import com.cens.mall.ware.entity.WareSkuEntity;
import com.cens.mall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CommodityFeignService commodityFeignService;
    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wareSkuEntityQueryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotEmpty(skuId)) {
            wareSkuEntityQueryWrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId)) {
            wareSkuEntityQueryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wareSkuEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        if (CollectionUtils.isEmpty(
                wareSkuDao.selectList(
                        new QueryWrapper<WareSkuEntity>()
                                .eq("sku_id", skuId)
                                .eq("ware_id", wareId)
                )
        )) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            R result = commodityFeignService.info(skuId);
            if (result.getCode() == 0) {
                Map<String, Object> map = (Map<String, Object>) result.get("skuInfo");
                wareSkuEntity.setSkuName((String) map.get("skuName"));
            }
            wareSkuDao.insert(wareSkuEntity);
        }
        wareSkuDao.addStock(skuId, wareId, skuNum);
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        return skuIds.stream()
                .map(
                        skuId -> {
                            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
                            Long count = baseMapper.getSkuStock(skuId);
                            skuHasStockVo.setSkuId(skuId);
                            skuHasStockVo.setHasStock(count != null && count > 0);
                            return skuHasStockVo;
                        }
                ).collect(Collectors.toList());
    }

    /**
     * 锁定库存
     * <p>
     * 库存解锁的场景：
     * 1、订单超时取消了
     * 2、用户手动取消订单
     * 3、生成订单中别的业务失败，导致订单回滚
     * 4、
     *
     * @param wareSkuLockVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        //保存库存工作单详情
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        List<OrderItemVo> lockItems = wareSkuLockVo.getLockItems();
        //查询商品库存信息
        List<SkuWareHasStock> wareHasStocks = lockItems.stream().map(
                item -> {
                    SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
                    Long skuId = item.getSkuId();
                    skuWareHasStock.setSkuId(skuId);
                    List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
                    skuWareHasStock.setWareIds(wareIds);
                    skuWareHasStock.setNum(item.getCount());
                    return skuWareHasStock;
                }
        ).collect(Collectors.toList());
        //锁定库存
        for (SkuWareHasStock wareHasStock : wareHasStocks) {
            Boolean isLocked = false;
            Long skuId = wareHasStock.getSkuId();
            List<Long> wareIds = wareHasStock.getWareIds();
            if (CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                Long acceptRows = wareSkuDao.lockSkuStock(skuId, wareId, wareHasStock.getNum());
                if (acceptRows > 0) {
                    isLocked = true;
                    //TODO 告诉MQ库存解锁成功
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(
                            null,
                            skuId,
                            null,
                            wareHasStock.getNum(),
                            wareOrderTaskEntity.getId(),
                            wareId,
                            1
                    );
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked",
                            StockLockedTo.builder()
                                    .id(wareOrderTaskEntity.getId())
                                    .detail(stockDetailTo)
                                    .build());
                    break;
                }
            }
            if (!isLocked) {
                //若锁定库存失败则抛出异常
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo stockLockedTo) {
        System.out.println("stock release ...");
        Long detailId = stockLockedTo.getDetail().getId();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if (detailEntity != null) {
            //解锁
            Long id = stockLockedTo.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if (data == null || data.getStatus() == 4) {
                    //订单不存在 或者 订单已经被取消
                    if (detailEntity.getLockStatus() == 1) {
                        unlockStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum(), detailEntity.getId());
                    }
                }
            } else {
                throw new RuntimeException("调用order feign service 失败");
            }
        }
    }

    /**
     * 防止订单服务出现异常，导致状态改不了，而库存消息先到，则什么事情都不会做，从而永远无法解锁库存
     *
     * @param orderTo
     */
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOne(
                new LambdaQueryWrapper<WareOrderTaskEntity>()
                        .eq(WareOrderTaskEntity::getOrderSn, orderSn)
        );
        List<WareOrderTaskDetailEntity> wareOrderTaskDetailEntities = wareOrderTaskDetailService.list(
                new LambdaQueryWrapper<WareOrderTaskDetailEntity>()
                        .eq(WareOrderTaskDetailEntity::getTaskId, wareOrderTaskEntity.getId())
                        .eq(WareOrderTaskDetailEntity::getLockStatus, 1)
        );
        if (CollectionUtils.isNotEmpty(wareOrderTaskDetailEntities)) {
            for (WareOrderTaskDetailEntity wareOrderTaskDetailEntity : wareOrderTaskDetailEntities) {
                unlockStock(
                        wareOrderTaskDetailEntity.getSkuId(),
                        wareOrderTaskDetailEntity.getWareId(),
                        wareOrderTaskDetailEntity.getSkuNum(),
                        wareOrderTaskDetailEntity.getId()
                );
            }
        }

    }

    private void unlockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        wareSkuDao.unlockStock(skuId, wareId, num);
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(taskDetailId);
        wareOrderTaskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(
                wareOrderTaskDetailEntity
        );
    }


    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareIds;
    }

}